
/*
 * openssl.c
 *		OpenSSL 库的封装。
 *
 * Copyright (c) 2001 Marko Kreen
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *	  notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *	  notice, this list of conditions and the following disclaimer in the
 *	  documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * contrib/pgcrypto/openssl.c
 */

#include "postgres.h"

#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/rand.h>

#include "px.h"
#include "utils/memutils.h"
#include "utils/resowner.h"

/*
 * 我们可能想要处理的最大长度。
 */
#define MAX_KEY		(512/8)
#define MAX_IV		(128/8)

/*
 * 哈希
 */

/*
 * 为了确保我们在中止时不泄露 OpenSSL 句柄，我们将 OSSLDigest
 * 对象保存在一个链表中，分配在 TopMemoryContext 中。我们使用
 * ResourceOwner 机制在中止时释放它们。
 */
typedef struct OSSLDigest
{
	const EVP_MD *algo;
	EVP_MD_CTX *ctx;

	ResourceOwner owner;
	struct OSSLDigest *next;
	struct OSSLDigest *prev;
} OSSLDigest;

static OSSLDigest *open_digests = NULL;
static bool digest_resowner_callback_registered = false;

static void fc_free_openssl_digest(OSSLDigest *fc_digest)
{
	EVP_MD_CTX_destroy(fc_digest->ctx);
	if (fc_digest->prev)
		fc_digest->prev->next = fc_digest->next;
	else
		open_digests = fc_digest->next;
	if (fc_digest->next)
		fc_digest->next->prev = fc_digest->prev;
	pfree(fc_digest);
}

/*
 * 在中止时关闭任何打开的 OpenSSL 句柄。
 */
static void fc_digest_free_callback(ResourceReleasePhase fc_phase,
					 bool fc_isCommit,
					 bool fc_isTopLevel,
					 void *fc_arg)
{
	OSSLDigest *fc_curr;
	OSSLDigest *fc_next;

	if (fc_phase != RESOURCE_RELEASE_AFTER_LOCKS)
		return;

	fc_next = open_digests;
	while (fc_next)
	{
		fc_curr = fc_next;
		fc_next = fc_curr->next;

		if (fc_curr->owner == CurrentResourceOwner)
		{
			if (fc_isCommit)
				elog(WARNING, "pgcrypto digest reference leak: digest %p still referenced", fc_curr);
			fc_free_openssl_digest(fc_curr);
		}
	}
}

static unsigned fc_digest_result_size(PX_MD *fc_h)
{
	OSSLDigest *fc_digest = (OSSLDigest *) fc_h->p.ptr;
	int			fc_result = EVP_MD_CTX_size(fc_digest->ctx);

	if (fc_result < 0)
		elog(ERROR, "EVP_MD_CTX_size() failed");

	return fc_result;
}

static unsigned fc_digest_block_size(PX_MD *fc_h)
{
	OSSLDigest *fc_digest = (OSSLDigest *) fc_h->p.ptr;
	int			fc_result = EVP_MD_CTX_block_size(fc_digest->ctx);

	if (fc_result < 0)
		elog(ERROR, "EVP_MD_CTX_block_size() failed");

	return fc_result;
}

static void fc_digest_reset(PX_MD *fc_h)
{
	OSSLDigest *fc_digest = (OSSLDigest *) fc_h->p.ptr;

	if (!EVP_DigestInit_ex(fc_digest->ctx, fc_digest->algo, NULL))
		elog(ERROR, "EVP_DigestInit_ex() failed");
}

static void fc_digest_update(PX_MD *fc_h, const uint8 *fc_data, unsigned fc_dlen)
{
	OSSLDigest *fc_digest = (OSSLDigest *) fc_h->p.ptr;

	if (!EVP_DigestUpdate(fc_digest->ctx, fc_data, fc_dlen))
		elog(ERROR, "EVP_DigestUpdate() failed");
}

static void fc_digest_finish(PX_MD *fc_h, uint8 *fc_dst)
{
	OSSLDigest *fc_digest = (OSSLDigest *) fc_h->p.ptr;

	if (!EVP_DigestFinal_ex(fc_digest->ctx, fc_dst, NULL))
		elog(ERROR, "EVP_DigestFinal_ex() failed");
}

static void fc_digest_free(PX_MD *fc_h)
{
	OSSLDigest *fc_digest = (OSSLDigest *) fc_h->p.ptr;

	fc_free_openssl_digest(fc_digest);
	pfree(fc_h);
}

static int	px_openssl_initialized = 0;

/* 公共函数 */

int px_find_digest(const char *fc_name, PX_MD **fc_res)
{
	const EVP_MD *fc_md;
	EVP_MD_CTX *fc_ctx;
	PX_MD	   *fc_h;
	OSSLDigest *fc_digest;

	if (!px_openssl_initialized)
	{
		px_openssl_initialized = 1;
		OpenSSL_add_all_algorithms();
	}

	if (!digest_resowner_callback_registered)
	{
		RegisterResourceReleaseCallback(fc_digest_free_callback, NULL);
		digest_resowner_callback_registered = true;
	}

	fc_md = EVP_get_digestbyname(fc_name);
	if (fc_md == NULL)
		return PXE_NO_HASH;

	/*
	 * 创建一个 OSSLDigest 对象，一个 OpenSSL MD 对象，和一个 PX_MD 对象。
	 * 顺序至关重要，以确保我们在内存不足或其他错误时不泄漏任何内容。
	 */
	fc_digest = MemoryContextAlloc(TopMemoryContext, sizeof(*fc_digest));

	fc_ctx = EVP_MD_CTX_create();
	if (!fc_ctx)
	{
		pfree(fc_digest);
		return PXE_CIPHER_INIT;
	}
	if (EVP_DigestInit_ex(fc_ctx, fc_md, NULL) == 0)
	{
		EVP_MD_CTX_destroy(fc_ctx);
		pfree(fc_digest);
		return PXE_CIPHER_INIT;
	}

	fc_digest->algo = fc_md;
	fc_digest->ctx = fc_ctx;
	fc_digest->owner = CurrentResourceOwner;
	fc_digest->next = open_digests;
	fc_digest->prev = NULL;
	open_digests = fc_digest;

	/* PX_MD 对象在当前内存上下文中分配。 */
	fc_h = palloc(sizeof(*fc_h));
	fc_h->result_size = fc_digest_result_size;
	fc_h->block_size = fc_digest_block_size;
	fc_h->reset = fc_digest_reset;
	fc_h->update = fc_digest_update;
	fc_h->finish = fc_digest_finish;
	fc_h->free = fc_digest_free;
	fc_h->p.ptr = (void *) fc_digest;

	*fc_res = fc_h;
	return 0;
}

/*
 * 加密
 *
 * 我们使用 OpenSSL 的 EVP* 函数系列。
 */

/*
 * 返回算法的 EVP 函数的原型，例如
 * EVP_aes_128_cbc()。
 */
typedef const EVP_CIPHER *(*ossl_EVP_cipher_func) (void);

/*
 * ossl_cipher 包含每种加密算法的静态信息。
 */
struct ossl_cipher
{
	int			(*init) (PX_Cipher *c, const uint8 *key, unsigned klen, const uint8 *iv);
	ossl_EVP_cipher_func cipher_func;
	int			block_size;
	int			max_key_size;
};

/*
 * OSSLCipher 包含使用加密算法的状态。每次调用 px_find_cipher() 
 * 时都会分配一个单独的 OSSLCipher 对象。
 *
 * 为了确保我们在中止时不泄露 OpenSSL 句柄，我们将 OSSLCipher 
 * 对象保存在一个链表中，分配在 TopMemoryContext 中。我们使用
 * ResourceOwner 机制在中止时释放它们。
 */
typedef struct OSSLCipher
{
	EVP_CIPHER_CTX *evp_ctx;
	const EVP_CIPHER *evp_ciph;
	uint8		key[MAX_KEY];
	uint8		iv[MAX_IV];
	unsigned	klen;
	unsigned	init;
	const struct ossl_cipher *ciph;

	ResourceOwner owner;
	struct OSSLCipher *next;
	struct OSSLCipher *prev;
} OSSLCipher;

static OSSLCipher *open_ciphers = NULL;
static bool cipher_resowner_callback_registered = false;

static void fc_free_openssl_cipher(OSSLCipher *fc_od)
{
	EVP_CIPHER_CTX_free(fc_od->evp_ctx);
	if (fc_od->prev)
		fc_od->prev->next = fc_od->next;
	else
		open_ciphers = fc_od->next;
	if (fc_od->next)
		fc_od->next->prev = fc_od->prev;
	pfree(fc_od);
}

/*
 * 在中止时关闭任何打开的 OpenSSL 加密句柄。
 */
static void fc_cipher_free_callback(ResourceReleasePhase fc_phase,
					 bool fc_isCommit,
					 bool fc_isTopLevel,
					 void *fc_arg)
{
	OSSLCipher *fc_curr;
	OSSLCipher *fc_next;

	if (fc_phase != RESOURCE_RELEASE_AFTER_LOCKS)
		return;

	fc_next = open_ciphers;
	while (fc_next)
	{
		fc_curr = fc_next;
		fc_next = fc_curr->next;

		if (fc_curr->owner == CurrentResourceOwner)
		{
			if (fc_isCommit)
				elog(WARNING, "pgcrypto cipher reference leak: cipher %p still referenced", fc_curr);
			fc_free_openssl_cipher(fc_curr);
		}
	}
}

/* 所有算法的公共例程 */

static unsigned fc_gen_ossl_block_size(PX_Cipher *fc_c)
{
	OSSLCipher *fc_od = (OSSLCipher *) fc_c->ptr;

	return fc_od->ciph->block_size;
}

static unsigned fc_gen_ossl_key_size(PX_Cipher *fc_c)
{
	OSSLCipher *fc_od = (OSSLCipher *) fc_c->ptr;

	return fc_od->ciph->max_key_size;
}

static unsigned fc_gen_ossl_iv_size(PX_Cipher *fc_c)
{
	unsigned	fc_ivlen;
	OSSLCipher *fc_od = (OSSLCipher *) fc_c->ptr;

	fc_ivlen = fc_od->ciph->block_size;
	return fc_ivlen;
}

static void fc_gen_ossl_free(PX_Cipher *fc_c)
{
	OSSLCipher *fc_od = (OSSLCipher *) fc_c->ptr;

	fc_free_openssl_cipher(fc_od);
	pfree(fc_c);
}

static int fc_gen_ossl_decrypt(PX_Cipher *fc_c, int fc_padding, const uint8 *fc_data, unsigned fc_dlen,
				 uint8 *fc_res, unsigned *fc_rlen)
{
	OSSLCipher *fc_od = fc_c->ptr;
	int			fc_outlen,
				fc_outlen2;

	if (!fc_od->init)
	{
		if (!EVP_DecryptInit_ex(fc_od->evp_ctx, fc_od->evp_ciph, NULL, NULL, NULL))
			return PXE_CIPHER_INIT;
		if (!EVP_CIPHER_CTX_set_padding(fc_od->evp_ctx, fc_padding))
			return PXE_CIPHER_INIT;
		if (!EVP_CIPHER_CTX_set_key_length(fc_od->evp_ctx, fc_od->klen))
			return PXE_CIPHER_INIT;
		if (!EVP_DecryptInit_ex(fc_od->evp_ctx, NULL, NULL, fc_od->key, fc_od->iv))
			return PXE_CIPHER_INIT;
		fc_od->init = true;
	}

	if (!EVP_DecryptUpdate(fc_od->evp_ctx, fc_res, &fc_outlen, fc_data, fc_dlen))
		return PXE_DECRYPT_FAILED;
	if (!EVP_DecryptFinal_ex(fc_od->evp_ctx, fc_res + fc_outlen, &fc_outlen2))
		return PXE_DECRYPT_FAILED;
	*fc_rlen = fc_outlen + fc_outlen2;

	return 0;
}

static int fc_gen_ossl_encrypt(PX_Cipher *fc_c, int fc_padding, const uint8 *fc_data, unsigned fc_dlen,
				 uint8 *fc_res, unsigned *fc_rlen)
{
	OSSLCipher *fc_od = fc_c->ptr;
	int			fc_outlen,
				fc_outlen2;

	if (!fc_od->init)
	{
		if (!EVP_EncryptInit_ex(fc_od->evp_ctx, fc_od->evp_ciph, NULL, NULL, NULL))
			return PXE_CIPHER_INIT;
		if (!EVP_CIPHER_CTX_set_padding(fc_od->evp_ctx, fc_padding))
			return PXE_CIPHER_INIT;
		if (!EVP_CIPHER_CTX_set_key_length(fc_od->evp_ctx, fc_od->klen))
			return PXE_CIPHER_INIT;
		if (!EVP_EncryptInit_ex(fc_od->evp_ctx, NULL, NULL, fc_od->key, fc_od->iv))
			return PXE_CIPHER_INIT;
		fc_od->init = true;
	}

	if (!EVP_EncryptUpdate(fc_od->evp_ctx, fc_res, &fc_outlen, fc_data, fc_dlen))
		return PXE_ENCRYPT_FAILED;
	if (!EVP_EncryptFinal_ex(fc_od->evp_ctx, fc_res + fc_outlen, &fc_outlen2))
		return PXE_ENCRYPT_FAILED;
	*fc_rlen = fc_outlen + fc_outlen2;

	return 0;
}

/* Blowfish */

/*
 * 检查是否支持强加密。一些 OpenSSL 安装
 * 仅支持短密钥，不幸的是 BF_set_key 不会返回任何
 * 错误值。该函数测试是否可以使用强密钥。
 */
static int fc_bf_check_supported_key_len(void)
{
	static const uint8 fc_key[56] = {
		0xf0, 0xe1, 0xd2, 0xc3, 0xb4, 0xa5, 0x96, 0x87, 0x78, 0x69,
		0x5a, 0x4b, 0x3c, 0x2d, 0x1e, 0x0f, 0x00, 0x11, 0x22, 0x33,
		0x44, 0x55, 0x66, 0x77, 0x04, 0x68, 0x91, 0x04, 0xc2, 0xfd,
		0x3b, 0x2f, 0x58, 0x40, 0x23, 0x64, 0x1a, 0xba, 0x61, 0x76,
		0x1f, 0x1f, 0x1f, 0x1f, 0x0e, 0x0e, 0x0e, 0x0e, 0xff, 0xff,
		0xff, 0xff, 0xff, 0xff, 0xff, 0xff
	};

	static const uint8 fc_data[8] = {0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10};
	static const uint8 fc_res[8] = {0xc0, 0x45, 0x04, 0x01, 0x2e, 0x4e, 0x1f, 0x53};
	uint8		fc_out[8];
	EVP_CIPHER_CTX *fc_evp_ctx;
	int			fc_outlen;
	int			fc_status = 0;

	/* 使用 448 位密钥进行加密并验证输出 */
	fc_evp_ctx = EVP_CIPHER_CTX_new();
	if (!fc_evp_ctx)
		return 0;
	if (!EVP_EncryptInit_ex(fc_evp_ctx, EVP_bf_ecb(), NULL, NULL, NULL))
		goto leave;
	if (!EVP_CIPHER_CTX_set_key_length(fc_evp_ctx, 56))
		goto leave;
	if (!EVP_EncryptInit_ex(fc_evp_ctx, NULL, NULL, fc_key, NULL))
		goto leave;

	if (!EVP_EncryptUpdate(fc_evp_ctx, fc_out, &fc_outlen, fc_data, 8))
		goto leave;

	if (memcmp(fc_out, fc_res, 8) != 0)
		goto leave;				/* 输出不匹配 -> 不支持强加密 */
	fc_status = 1;

leave:
	EVP_CIPHER_CTX_free(fc_evp_ctx);
	return fc_status;
}

static int fc_bf_init(PX_Cipher *fc_c, const uint8 *fc_key, unsigned fc_klen, const uint8 *fc_iv)
{
	OSSLCipher *fc_od = fc_c->ptr;
	unsigned	fc_bs = fc_gen_ossl_block_size(fc_c);
	static int	fc_bf_is_strong = -1;

	/*
	 * 测试密钥长度是否被支持。BF_set_key 默默地截断大密钥，这可能
	 * 在用户从一个服务器传输加密数据到另一个服务器时造成问题。
	 */

	if (fc_bf_is_strong == -1)
		fc_bf_is_strong = fc_bf_check_supported_key_len();

	if (!fc_bf_is_strong && fc_klen > 16)
		return PXE_KEY_TOO_BIG;

	/* 密钥长度被支持。我们可以使用它。 */
	fc_od->klen = fc_klen;
	memcpy(fc_od->key, fc_key, fc_klen);

	if (fc_iv)
		memcpy(fc_od->iv, fc_iv, fc_bs);
	else
		memset(fc_od->iv, 0, fc_bs);
	return 0;
}

/* DES */

static int fc_ossl_des_init(PX_Cipher *fc_c, const uint8 *fc_key, unsigned fc_klen, const uint8 *fc_iv)
{
	OSSLCipher *fc_od = fc_c->ptr;
	unsigned	fc_bs = fc_gen_ossl_block_size(fc_c);

	fc_od->klen = 8;
	memset(fc_od->key, 0, 8);
	memcpy(fc_od->key, fc_key, fc_klen > 8 ? 8 : fc_klen);

	if (fc_iv)
		memcpy(fc_od->iv, fc_iv, fc_bs);
	else
		memset(fc_od->iv, 0, fc_bs);
	return 0;
}

/* DES3 */

static int fc_ossl_des3_init(PX_Cipher *fc_c, const uint8 *fc_key, unsigned fc_klen, const uint8 *fc_iv)
{
	OSSLCipher *fc_od = fc_c->ptr;
	unsigned	fc_bs = fc_gen_ossl_block_size(fc_c);

	fc_od->klen = 24;
	memset(fc_od->key, 0, 24);
	memcpy(fc_od->key, fc_key, fc_klen > 24 ? 24 : fc_klen);

	if (fc_iv)
		memcpy(fc_od->iv, fc_iv, fc_bs);
	else
		memset(fc_od->iv, 0, fc_bs);
	return 0;
}

/* CAST5 */

static int fc_ossl_cast_init(PX_Cipher *fc_c, const uint8 *fc_key, unsigned fc_klen, const uint8 *fc_iv)
{
	OSSLCipher *fc_od = fc_c->ptr;
	unsigned	fc_bs = fc_gen_ossl_block_size(fc_c);

	fc_od->klen = fc_klen;
	memcpy(fc_od->key, fc_key, fc_klen);

	if (fc_iv)
		memcpy(fc_od->iv, fc_iv, fc_bs);
	else
		memset(fc_od->iv, 0, fc_bs);
	return 0;
}

/* AES */

static int fc_ossl_aes_init(PX_Cipher *fc_c, const uint8 *fc_key, unsigned fc_klen, const uint8 *fc_iv)
{
	OSSLCipher *fc_od = fc_c->ptr;
	unsigned	fc_bs = fc_gen_ossl_block_size(fc_c);

	if (fc_klen <= 128 / 8)
		fc_od->klen = 128 / 8;
	else if (fc_klen <= 192 / 8)
		fc_od->klen = 192 / 8;
	else if (fc_klen <= 256 / 8)
		fc_od->klen = 256 / 8;
	else
		return PXE_KEY_TOO_BIG;

	memcpy(fc_od->key, fc_key, fc_klen);

	if (fc_iv)
		memcpy(fc_od->iv, fc_iv, fc_bs);
	else
		memset(fc_od->iv, 0, fc_bs);

	return 0;
}

static int fc_ossl_aes_ecb_init(PX_Cipher *fc_c, const uint8 *fc_key, unsigned fc_klen, const uint8 *fc_iv)
{
	OSSLCipher *fc_od = fc_c->ptr;
	int			fc_err;

	fc_err = fc_ossl_aes_init(fc_c, fc_key, fc_klen, fc_iv);
	if (fc_err)
		return fc_err;

	switch (fc_od->klen)
	{
		case 128 / 8:
			fc_od->evp_ciph = EVP_aes_128_ecb();
			break;
		case 192 / 8:
			fc_od->evp_ciph = EVP_aes_192_ecb();
			break;
		case 256 / 8:
			fc_od->evp_ciph = EVP_aes_256_ecb();
			break;
		default:
			/* 不应该发生 */
			fc_err = PXE_CIPHER_INIT;
			break;
	}

	return fc_err;
}

static int fc_ossl_aes_cbc_init(PX_Cipher *fc_c, const uint8 *fc_key, unsigned fc_klen, const uint8 *fc_iv)
{
	OSSLCipher *fc_od = fc_c->ptr;
	int			fc_err;

	fc_err = fc_ossl_aes_init(fc_c, fc_key, fc_klen, fc_iv);
	if (fc_err)
		return fc_err;

	switch (fc_od->klen)
	{
		case 128 / 8:
			fc_od->evp_ciph = EVP_aes_128_cbc();
			break;
		case 192 / 8:
			fc_od->evp_ciph = EVP_aes_192_cbc();
			break;
		case 256 / 8:
			fc_od->evp_ciph = EVP_aes_256_cbc();
			break;
		default:
			/* 不应该发生 */
			fc_err = PXE_CIPHER_INIT;
			break;
	}

	return fc_err;
}

/*
 * 别名
 */

static PX_Alias ossl_aliases[] = {
	{"bf", "bf-cbc"},
	{"blowfish", "bf-cbc"},
	{"blowfish-cbc", "bf-cbc"},
	{"blowfish-ecb", "bf-ecb"},
	{"blowfish-cfb", "bf-cfb"},
	{"des", "des-cbc"},
	{"3des", "des3-cbc"},
	{"3des-ecb", "des3-ecb"},
	{"3des-cbc", "des3-cbc"},
	{"cast5", "cast5-cbc"},
	{"aes", "aes-cbc"},
	{"rijndael", "aes-cbc"},
	{"rijndael-cbc", "aes-cbc"},
	{"rijndael-ecb", "aes-ecb"},
	{NULL}
};

static const struct ossl_cipher ossl_bf_cbc = {
	fc_bf_init,
	EVP_bf_cbc,
	64 / 8, 448 / 8
};

static const struct ossl_cipher ossl_bf_ecb = {
	fc_bf_init,
	EVP_bf_ecb,
	64 / 8, 448 / 8
};

static const struct ossl_cipher ossl_bf_cfb = {
	fc_bf_init,
	EVP_bf_cfb,
	64 / 8, 448 / 8
};

static const struct ossl_cipher ossl_des_ecb = {
	fc_ossl_des_init,
	EVP_des_ecb,
	64 / 8, 64 / 8
};

static const struct ossl_cipher ossl_des_cbc = {
	fc_ossl_des_init,
	EVP_des_cbc,
	64 / 8, 64 / 8
};

static const struct ossl_cipher ossl_des3_ecb = {
	fc_ossl_des3_init,
	EVP_des_ede3_ecb,
	64 / 8, 192 / 8
};

static const struct ossl_cipher ossl_des3_cbc = {
	fc_ossl_des3_init,
	EVP_des_ede3_cbc,
	64 / 8, 192 / 8
};

static const struct ossl_cipher ossl_cast_ecb = {
	fc_ossl_cast_init,
	EVP_cast5_ecb,
	64 / 8, 128 / 8
};

static const struct ossl_cipher ossl_cast_cbc = {
	fc_ossl_cast_init,
	EVP_cast5_cbc,
	64 / 8, 128 / 8
};

static const struct ossl_cipher ossl_aes_ecb = {
	fc_ossl_aes_ecb_init,
	NULL,						/* EVP_aes_XXX_ecb()，在初始化函数中确定 */
	128 / 8, 256 / 8
};

static const struct ossl_cipher ossl_aes_cbc = {
	fc_ossl_aes_cbc_init,
	NULL,						/* EVP_aes_XXX_cbc()，在初始化函数中确定 */
	128 / 8, 256 / 8
};

/*
 * 特殊处理程序
 */
struct ossl_cipher_lookup
{
	const char *name;
	const struct ossl_cipher *ciph;
};

static const struct ossl_cipher_lookup ossl_cipher_types[] = {
	{"bf-cbc", &ossl_bf_cbc},
	{"bf-ecb", &ossl_bf_ecb},
	{"bf-cfb", &ossl_bf_cfb},
	{"des-ecb", &ossl_des_ecb},
	{"des-cbc", &ossl_des_cbc},
	{"des3-ecb", &ossl_des3_ecb},
	{"des3-cbc", &ossl_des3_cbc},
	{"cast5-ecb", &ossl_cast_ecb},
	{"cast5-cbc", &ossl_cast_cbc},
	{"aes-ecb", &ossl_aes_ecb},
	{"aes-cbc", &ossl_aes_cbc},
	{NULL}
};

/* 公共函数 */

int px_find_cipher(const char *fc_name, PX_Cipher **fc_res)
{
	const struct ossl_cipher_lookup *fc_i;
	PX_Cipher  *fc_c = NULL;
	EVP_CIPHER_CTX *fc_ctx;
	OSSLCipher *fc_od;

	fc_name = px_resolve_alias(ossl_aliases, fc_name);
	for (fc_i = ossl_cipher_types; fc_i->name; fc_i++)
		if (strcmp(fc_i->name, fc_name) == 0)
			break;
	if (fc_i->name == NULL)
		return PXE_NO_CIPHER;

	if (!cipher_resowner_callback_registered)
	{
		RegisterResourceReleaseCallback(fc_cipher_free_callback, NULL);
		cipher_resowner_callback_registered = true;
	}

	/*
	 * 创建一个 OSSLCipher 对象，一个 EVP_CIPHER_CTX 对象和一个 PX_Cipher。
	 * 顺序至关重要，以确保我们在内存不足或其他错误时不泄漏任何内容。
	 */
	fc_od = MemoryContextAllocZero(TopMemoryContext, sizeof(*fc_od));
	fc_od->ciph = fc_i->ciph;

	/* 分配一个 EVP_CIPHER_CTX 对象。 */
	fc_ctx = EVP_CIPHER_CTX_new();
	if (!fc_ctx)
	{
		pfree(fc_od);
		return PXE_CIPHER_INIT;
	}

	fc_od->evp_ctx = fc_ctx;
	fc_od->owner = CurrentResourceOwner;
	fc_od->next = open_ciphers;
	fc_od->prev = NULL;
	open_ciphers = fc_od;

	if (fc_i->ciph->cipher_func)
		fc_od->evp_ciph = fc_i->ciph->cipher_func();

	/* PX_Cipher 在当前内存上下文中分配 */
	fc_c = palloc(sizeof(*fc_c));
	fc_c->block_size = fc_gen_ossl_block_size;
	fc_c->key_size = fc_gen_ossl_key_size;
	fc_c->iv_size = fc_gen_ossl_iv_size;
	fc_c->free = fc_gen_ossl_free;
	fc_c->init = fc_od->ciph->init;
	fc_c->encrypt = fc_gen_ossl_encrypt;
	fc_c->decrypt = fc_gen_ossl_decrypt;
	fc_c->ptr = fc_od;

	*fc_res = fc_c;
	return 0;
}
